import 'package:flower/components/custom_toast.dart';
import 'package:flower/model/base_model.dart';
import 'package:flower/utils/my_icons.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../../../components/cached_image_widget.dart';
import '../../../../config/service_url.dart';
import '../../../../model/user_info.dart';
import '../../../../utils/http_util.dart';

class Personal extends StatefulWidget {
  const Personal({super.key});

  @override
  State<Personal> createState() => _Personal();
}

class _Personal extends State<Personal> {
  UserInfoData userInfoData = UserInfoData(
      id: 1,
      username: "liuhaha",
      password: "",
      phone: "17318615767",
      email: "4568799@qq.com",
      nickname: "刘哈哈",
      point: 0,
      avatar: "hhtttppp",
      gender: 0,
      description: "这个人很懒~",
      vip: 3,
      role: 1,
      createDate: "2024-2-1");

  final _nicknameController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  bool isMale = false;
  bool isFemale = false;
  bool isSecret = false;
  final ImagePicker _picker = ImagePicker();
  File? _image;

  @override
  void initState() {
    super.initState();
    queryMemberInfo();
  }

  void queryMemberInfo() async {
    Response result = await HttpUtil.get(getPersonalInfo);
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result.data);
    setState(() {
      userInfoData = userInfoModel.data!;
      _nicknameController.text = userInfoData.nickname;
      _descriptionController.text = userInfoData.description;
      _emailController.text = userInfoData.email ?? "";
      _phoneController.text = userInfoData.phone ?? "";
      _setSelectedGender(userInfoData.gender); // 确保性别设置在此处调用
    });
  }

  void _setSelectedGender(int gender) {
    setState(() {
      isMale = gender == 1;
      isFemale = gender == 0;
      isSecret = gender == 2;
    });
  }

  int _getSelectedGender() {
    if (isMale) return 1;
    if (isFemale) return 0;
    if (isSecret) return 2;
    return 0;
  }

  Future<void> _pickImage() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      Response response =
          await HttpUtil.uploadImage(uploadUserAvatar, File(pickedFile.path));

      BaseModel baseModel = BaseModel.fromJson(response.data);
      if (baseModel.code == 1) {
        // 上传成功
        CustomToast.showSuccessToast("上传成功");
        setState(() {
          userInfoData.avatar = baseModel.data;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人资料'),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          userAvatar(),
          userInfo(),
        ],
      ),
    );
  }

  Widget userInfo() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: TextEditingController(text: userInfoData.username),
            decoration: const InputDecoration(
              labelText: '账户名',
              border: OutlineInputBorder(),
            ),
            readOnly: true,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _nicknameController,
            decoration: const InputDecoration(
              labelText: '昵称',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 16),
          CheckboxListTile(
            title: const Row(
              children: [
                Icon(Icons.male),
                SizedBox(width: 8),
                Text('男性'),
              ],
            ),
            value: isMale,
            onChanged: (bool? value) {
              setState(() {
                isMale = value ?? false;
                if (isMale) {
                  isFemale = false;
                  isSecret = false;
                }
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
          CheckboxListTile(
            title: const Row(
              children: [
                Icon(Icons.female),
                SizedBox(width: 8),
                Text('女性'),
              ],
            ),
            value: isFemale,
            onChanged: (bool? value) {
              setState(() {
                isFemale = value ?? false;
                if (isFemale) {
                  isMale = false;
                  isSecret = false;
                }
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
          CheckboxListTile(
            title: const Row(
              children: [
                Icon(Icons.help),
                SizedBox(width: 8),
                Text('保密'),
              ],
            ),
            value: isSecret,
            onChanged: (bool? value) {
              setState(() {
                isSecret = value ?? false;
                if (isSecret) {
                  isMale = false;
                  isFemale = false;
                }
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _phoneController,
            decoration: const InputDecoration(
              labelText: '手机号',
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.phone,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _emailController,
            decoration: const InputDecoration(
              labelText: '邮箱',
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.emailAddress,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _descriptionController,
            decoration: const InputDecoration(
              labelText: '描述一下自己啦啦啦啦',
              border: OutlineInputBorder(),
            ),
            maxLines: 6,
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: _updateUserInfo,
                child: const Text('保存'),
              ),
              const SizedBox(width: 16),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text('取消'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _updateUserInfo() async {
    userInfoData.nickname = _nicknameController.text;
    userInfoData.description = _descriptionController.text;
    userInfoData.email = _emailController.text;
    userInfoData.phone = _phoneController.text;
    userInfoData.gender = _getSelectedGender();

    Map<String, dynamic> map = <String, dynamic>{};
    map["nickname"] = _nicknameController.text;
    map["description"] = _descriptionController.text;
    map["email"] = _emailController.text;
    map["phone"] = _phoneController.text;
    map["gender"] = _getSelectedGender();
    map["avatar"] = userInfoData.avatar;

    Response result = await HttpUtil.post(updateUserInfo, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      CustomToast.showSuccessToast("保存成功");
      Navigator.of(context).pop();
    } else {
      CustomToast.showErrorToast(baseModel.msg!);
    }
  }

  Widget userAvatar() {
    return Stack(
      children: [
        Container(
          margin: const EdgeInsets.only(left: 125, top: 10.0),
          child: Column(
            children: [
              InkWell(
                onTap: _pickImage,
                child: ClipOval(
                  child: _image != null
                      ? Image.file(
                          _image!,
                          width: 80,
                          height: 80,
                          fit: BoxFit.cover,
                        )
                      : CachedImageWidget(
                          80,
                          80,
                          userInfoData.avatar,
                          fit: BoxFit.cover,
                        ),
                ),
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: () {
                  CustomToast.showWarningToast("该功能暂未开发~");
                },
                child: const Text(
                  'VIP充值入口',
                  style: TextStyle(color: Colors.deepOrange, fontSize: 10),
                ),
              ),
            ],
          ),
        ),
        const Positioned(
          left: 210,
          top: 60,
          child: Icon(
            MyIcons.vip,
            color: Colors.deepOrange,
          ),
        ),
      ],
    );
  }
}
